<template>
  <el-dialog v-model="dialogVisible" title="Tips" width="30%" destroy-on-close>
    <vue-from v-bind="modalConfig" v-model="formData"></vue-from>
    <slot></slot>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmClick">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import VueFrom from "@/base-ui/form";
import { useStore } from "@/store";
import { defineComponent, ref, watch } from "vue";
export default defineComponent({
  components: { VueFrom },
  props: {
    modalConfig: {
      type: Object,
    },
    modalInfo: {
      type: Object,
      default: () => ({}),
    },
    otherInfo: {
      type: Object,
      default: () => ({}),
    },
    pageName: {
      type: String,
      default: () => "",
    },
  },
  setup(props) {
    const store = useStore();

    const formData = ref<any>({});

    const dialogVisible = ref(false);

    const handleConfirmClick = () => {
      dialogVisible.value = false;
      if (Object.keys(props.modalInfo).length) {
        // 编辑
        store.dispatch("systemModule/editPageDataActions", {
          pageName: props.pageName,
          editData: { ...formData.value, ...props.otherInfo },
          id: props.modalInfo.id,
        });
      } else {
        // 新建
        store.dispatch("systemModule/createPageDataActions", {
          pageName: props.pageName,
          newData: { ...formData.value, ...props.otherInfo },
        });
      }
    };

    watch(
      () => props.modalInfo,
      (newValue) => {
        for (const item of props.modalConfig?.formItems) {
          formData.value[`${item.field}`] = newValue[`${item.field}`];
        }
      }
    );
    return {
      dialogVisible,
      formData,
      handleConfirmClick,
    };
  },
});
</script>
